/**
 * hb.grid 基于jQuery
 * 
 * @version 1.0
 * @author LianYiFei
 * TO-DO 静态数据功能(尚未实现)
 */

(function($) {
	var hb = this.hb || {};
	this.hb = hb;
	grid = function(model) {
		return new grid.prototype.init(model);
	};
	grid.prototype = {
		init : function(model) {
			this.p = $.extend(true,{
				url: '',
				data:[],
				wrapper: $('#pageWrapper'),
				pageSupport:"result",
				pageNo: 1,
				pageSize: 10,
				parameters: {},
				colModel: [],
				root: 'result.resultList',
				ordinal: false,
				ordinalWidth: 30,
				displayTotalRecord: false,
				showHint: false,
				hint: '',
				headClass: '',
				skin:'deafult',
				rowClass: '',
				oddRowClass: '',
				evenRowClass: '',
				callback: {}
			},model);
			this._gridTable = $('<table id="hb-grid-id" border="0" cellspacing="0"></table>').addClass('grid');
			if(this.p.skin == 'deafult'){
				this._gridTable.addClass('hb-grid');
			}
			this._rowContainer = $('<tbody/>');
			this._createHeader();
			this.isRowSelected = false;
			this.selectedRow = {};
			this.xmlhttp = null;
		},
		
		_showMessage : function() {
			var wrapper = this.p.wrapper;
			if (!$('#grid_loading')[0]) {
				var $loading = $('<div/>').attr('id', 'grid_loading').html('数据载入中...').appendTo($('body'));
			}
			if (!wrapper.is(':hidden')) {			
				$('#grid_loading').css('top',wrapper.offset().top + (wrapper.height() - $('#grid_loading').height())/2 + 'px' )
					.css('left',wrapper.offset().left + (wrapper.width()-$('#grid_loading').width())/2 + 'px' );
			}
			$('#grid_loading').show();
		},
		
		_hideMessage : function() {
			$('#grid_loading').hide();
		},
		
		_beforeShow: function() {},
		
		_afterShow: function() {},
		
		_display: function() {
			this._showMessage();
			this._createGrid();
		},
		_buildData: function(data){
			var _data = data;
			var namePaths = this.p.root.split(".");
			for(var i=0;i<namePaths.length;i++){
				_data = _data[namePaths[i]];
			}
			this.data = _data;
			this.pageSupport = data[this.p.pageSupport?this.p.pageSupport:"pageSupport"];
		},
		show : function(wrapper) {
			if(wrapper){
				this.p.wrapper = typeof wrapper === 'string'? $('#'+wrapper):$(wrapper);
			}
//			this._beforeShow();
			this._display();
//			this._afterShow();
		},
		data: function(data){
			this._buildData(data);
			return this;
		},
		refresh: function() {
			if (arguments.length > 0){
				this.p.pageNo = 1;
				this.p = $.extend(true,this.p,arguments[0]);
				if (arguments.length === 3 && arguments[2]) {
					this.p.parameters = arguments[0].parameters;
				}
			}
			if (typeof arguments[1] !== undefined && arguments[1]) {
				this._gridTable.empty();
				this._createHeader();
			}
			this._display();
		},
		refreshPage: function() {
			if (arguments.length > 0){
				this.p = $.extend(true,this.p,arguments[0]);
				if (arguments.length === 3 && arguments[2]) {
					this.p.parameters = arguments[0].parameters;
				}
			}
			if (typeof arguments[1] !== undefined && arguments[1]) {
				this._gridTable.empty();
				this._createHeader();
			}
			this._display();
		},
		
		selectIndex: function(index) {
			this.p.wrapper.find('#row_' + index).click(); 
		},
		
		_createHeader: function() {
			var cm = this.p.colModel;
			var thead = $('<thead/>');
			var header = $('<tr/>').addClass(this.p.headClass);
			if (this.p.ordinal){
				header.append($('<th/>').css('width',this.p.ordinalWidth+'px').html('序号'));
			}
			$.each(cm,function(index,col){
				var cell = $('<th/>').css('width',col.width||'').addClass(col.className||'').html(col.title||'');
				if (typeof col.headSelect !== 'undefined'){
					var select = $('<select/>');
					$.each(col.headSelect.options,function(i,option) {
						select[0].options.add(new Option(option.text,option.value)); 
					});
					select.bind(col.headSelect.eventName||'change',function(){
						col.headSelect.handler(select);
					});
					cell.empty().append(select);
				}
				header.append(cell);
			});
			thead.append(header);
			this._gridTable.append(thead);
		},
		
		_createGrid: function() {
			var _this = this;
			if(!_this.p.url || _this.p.url == ''){
				_this._renderData(_this.data);
				return;
			}
			// 从服务器抓取数据并调用addContent添加分页内容
			if (this.xmlhttp !== null){
				this.xmlhttp.onreadystatechange = function() {};
				this.xmlhttp.abort();
				this.xmlhttp = null;
			}
			this.xmlhttp = $.ajax({
				type: 'POST',
				url: _this.p.url,
				data: $.extend(_this.p.parameters,{
					_req_json_curpageno: _this.p.pageNo,
					_req_json_pagesize: _this.p.pageSize
				}),
				dataType: 'json',
				success: function(data) {
					_this._buildData(data);
					_this._renderData();
				},
				error: function(){
					alert('数据加载失败...');
				},
				complete: function(){
					_this._hideMessage();
				}
			});
		},
		_renderData: function(){
			var _this = this;
			_this._addContent();
			if (_this.p.callback.onload !== undefined) {
				_this.p.callback.onload(_this);
			}
		},
		// 添加分页内容
		_addContent: function(){
			
			if(this.p.wrapper){
				this.p.wrapper.empty();
			}
			this._createPage(this.data);
			this._createNav(this.pageSupport);
		},
		
		_createPage: function(records) {
			var _this = this;
			if (_this._rowContainer){
				_this._rowContainer.empty();
			}
			// 清除选中行数据
			_this.isRowSelected = false;
			_this.selectedRow = {};
			// 记录为空，创建一空行
			if (records.length == 0) {
				var emptyTr = $('<tr/>');
				if (_this.p.ordinal) {emptyTr.append($('<td>&nbsp;</td>'));}
				for (var i = 0; i < _this.p.colModel.length; i++) {
					emptyTr.append($('<td>&nbsp;</td>'));
				}
				_this._rowContainer.append(emptyTr);
			}
			$.each(records, function(rIndex,record) {
				record['rindex']=rIndex;//追加行号----------------------------------------------------------
				var row = $('<tr/>').attr('id','row_' + (rIndex + 1)).addClass(_this.p.rowClass).attr('title',_this.p.showHint?_this.p.hint:'');
				// 若有需要在这里加上奇偶行样式
				// 显示行号为true,创建行号
				if (_this.p.ordinal) {
					row.append($('<td/>').css('width',_this.p.ordinalWidth+'px').addClass('grid_ordinal').html((_this.p.pageNo-1)*_this.p.pageSize+rIndex+1));
				}
				$.each(_this.p.colModel,function(index,col) {
					var cell = $('<td/>').attr('id',col.id + (rIndex + 1)).addClass(col.className||'').css('width',col.width||'');
					if (typeof col.rule !== 'undefined') {
						var result = col.rule(record[col.id],record,cell);
						if (typeof result === 'string'){
							cell.html(result||'&nbsp;');
						}else if (result instanceof jQuery){
							cell.append(result);
						}else {
							cell.append(_this._buildCell(result,record));
						}
					}else {
						//  || 运算符  0 特殊
						cell.html(record[col.id] === 0 ? '0' : record[col.id]||'&nbsp;');
					}
					row.append(cell);
				});
				// IE6不支持CSS伪类
				if ($.browser.msie && $.browser.version === '6.0') {				
					row.hover(function(){$(this).removeClass('row_mouseout').addClass('row_mouseover');},
							function(){$(this).removeClass('row_mouseover').addClass('row_mouseout');});
					row.bind('click',function() {
						if (_this.isRowSelected){
							_this.selectedRow.el.removeClass('row_mousedown');
							_this.selectedRow.el.hover(function(){$(this).removeClass('row_mouseout').addClass('row_mouseover');},
								function(){$(this).removeClass('row_mouseover').addClass('row_mouseout');});
						}
						row.unbind('mouseenter').unbind('mouseleave');
						row.removeClass('row_mouseover').addClass('row_mousedown');
						_this.isRowSelected = true;
						_this.selectedRow.data = record;
						_this.selectedRow.el = row;
						if (_this.p.callback.click !== undefined){
							_this.p.callback.click(record,row);
						}
					});
				}
				else { // 非IE6通过伪类控制鼠标移入移出
					row.bind('click',function() {
						if (_this.isRowSelected){
							_this.selectedRow.el.removeClass('row_mousedown');
						}
						row.addClass('row_mousedown');
						_this.isRowSelected = true;
						_this.selectedRow.data = record;
						_this.selectedRow.el = row;
						if (_this.p.callback.click !== undefined){
							_this.p.callback.click(record,row);
						}
					});
				}
				if (_this.p.callback.dblclick !== undefined){
						row.bind('dblclick',function(){_this.p.callback.dblclick(record,row);});
				}
				_this._rowContainer.append(row);
			});
			_this._gridTable.append(_this._rowContainer);
			_this.p.wrapper.append(_this._gridTable);
		},
		
		_buildCell: function(obj,record) {
			var cellChild;
			switch(obj.type){
				case 'button':
					cellChild = $('<button type="button"/>').addClass('btn_mouseout').attr(obj.attr||{}).html(obj.text||'');
					cellChild.bind('mouseout',function(){this.className = 'btn_mouseout';});
					cellChild.bind('mouseover',function(){this.className = 'btn_mouseover';});
					break;
				case 'link':
					cellChild = $('<a/>').attr(obj.attr||{}).html(obj.text||'');
					break;
				case 'checkbox':
					cellChild = $('<input type="checkbox"/>').attr(obj.attr||{}).val(obj.value);
					break;
				case 'radio':
					cellChild = $('<input type="radio"/>').attr(obj.attr||{}).val(obj.value);
					break;
				default:
					return '';
			}
			if (typeof obj.handler !== 'undefined'){
				// 阻止事件冒泡，如有需要控制可再加个判断条件(isStopPropagation)
				cellChild.bind('click',function(event){event.stopPropagation();obj.handler(record);});
			}
			return cellChild;
		},
		
		_toPage: function(pageNo) {
			this.p.pageNo = pageNo;
			this.show();
		},
		_createNav: function(pageSupport){
			var _this = this;
			if(!pageSupport){
				return;
			}
			var totalRecord = pageSupport.totalRecord;
			var curPageNo = pageSupport.curPageNo;
			var totalPage = pageSupport.totalPage === 0 ? 1 : pageSupport.totalPage;
			var pageSize = pageSupport.pageSize;
			// 清空内容，解除绑定的事件
			_this.p.navWrapper = $('<div/>').attr('id','grid_navWrapper').width(this._gridTable.width()+1);
			_this.p.wrapper.append(_this.p.navWrapper);
			
			var navigation = $('<div/>').addClass('grid_navigation');
			var pageInfoStart = $('<span/>').addClass('pageinfo').html('第');
			var pageInfoEnd = $('<span/>').addClass('pageinfo').html('页/共'+totalPage+'页');
			var pageInput = $('<input type="text">').attr('id','pageInput').val(curPageNo)
							.bind('keydown',function(event){_this._inputKeyDown(event,pageInput,curPageNo,totalPage);});
			var inputSpan =  $('<span/>').addClass('input').append(pageInput);
			var firstPage = $('<span/>').attr('title','首页').addClass('firstpage').html('首页');
			var previousPage = $('<span/>').attr('title','上一页').addClass('previouspage').html('上一页');
			var nextPage = $('<span/>').attr('title','下一页').addClass('nextpage').html('下一页');
			var lastPage = $('<span/>').attr('title','末页').addClass('lastpage').html('末页');
			if (curPageNo > 1){
				firstPage.addClass('f_on');
				firstPage.bind('click',function(){_this._toPage(1);});
			}
			if (curPageNo > 1) {
				previousPage.addClass('p_on');
				previousPage.bind('click',function(){_this._toPage(curPageNo - 1);});
			}
			if (curPageNo < totalPage){
				nextPage.addClass('n_on');
				nextPage.bind('click',function(){_this._toPage(curPageNo + 1);});
			}
			if (curPageNo != totalPage){
				lastPage.addClass('l_on');
				lastPage.bind('click',function(){_this._toPage(totalPage);});
			}
			if (_this.p.callback.pageChange!== undefined){
							_this.p.callback.pageChange(curPageNo,totalPage);
						};
			
			navigation.append(firstPage);
			navigation.append(previousPage);
			navigation.append(nextPage);
			navigation.append(lastPage);
			
			navigation.append(pageInfoStart);
			navigation.append(inputSpan);
			navigation.append(pageInfoEnd);
			
			if (_this.p.displayTotalRecord){
				navigation.append($('<span/>').addClass('title').html('每页'+pageSize+'条/总共'+totalRecord+'条'));
			}
			_this.p.navWrapper.append(navigation);
		},
		
		_inputKeyDown: function(e,input,curPageNo,totalPage){
			var currKey = e.keyCode || e.which || e.charCode;
			// KEY_RETURN 13 回车键常量
			if(currKey == 13){
				var reg = /^[0-9]*[1-9][0-9]*$/;
				if(!reg.test(input.val()) || parseInt(input.val()) > totalPage){
					input.val(curPageNo);
				}
				else{
					this._toPage(input.val());
				}
			}
		}
	};
	// 引用grid的原型
	grid.prototype.init.prototype = grid.prototype;
	$.extend(hb, {grid : grid});
})(jQuery);

